<template>
  <view class="product-detail">
    <view class="product-image">
      <image src='../../static/logo.png' mode="aspectFill" />
    </view>
    <view class="product-info">
      <view class="product-name">商品名称：{{ products.goods_name }}</view>
      <view class="product-code">商品编号：{{ products.goods_sn }}</view>
	  <view class="product-code">所属分类：{{ products.category_name }}</view>
      <view class="product-cost">成本价：￥{{ products.goods_price_in }}</view>
      <view class="product-sale">销售价：￥{{ products.goods_price_out }}</view>
      <view class="product-status">当前状态：{{ products.goods_status }}</view>
    </view>
    <view class="action-buttons">
      <button class="edit-button" @click="showProductModal = true">编辑商品</button>
      <button class="shelve-button" @click="shelveProduct">
        <span v-if="products.goods_status === '下架'">上架</span>
        <span v-if="products.goods_status === '上架'">下架</span>
      </button>
    </view>
    
    <!-- 新增商品弹窗 -->
    <view v-if="showProductModal" class="modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">编辑商品</text>
        </view>
        <view class="modal-body">
          <view class="input-label">商品编号</view>
          <input type="text" v-model="products.goods_sn" placeholder="商品编号" class="input-field-rounded" :disabled="true"/>
          
          <view class="input-label">商品名称</view>
          <input type="text" v-model="products.goods_name" placeholder="商品名称" class="input-field-rounded" />
          
          <view class="input-label">商品规格</view>
          <input type="text" v-model="products.goods_spec" placeholder="商品规格" class="input-field-rounded" />
		
          
          <view class="input-label">成本价</view>
          <input type="text" v-model="products.goods_price_in" placeholder="成本价" class="input-field-rounded" />
          
          <view class="input-label">销售价</view>
          <input type="text" v-model="products.goods_price_out" placeholder="销售价" class="input-field-rounded" />
        </view>
        <view class="modal-footer">
          <button @click="submitProduct" class="action-button">提交</button>
          <button @click="HideModel" class="action-button">取消</button>
        </view>
      </view>
    </view>
	
	
	
	<!-- 绑定仓库弹窗 -->
	<view v-if="showWareHouseModal" class="modal">
	  <view class="modal-content">
	    <view class="modal-header">
	      <text class="modal-title">绑定仓库</text>
	    </view>
	    <view class="modal-body">
		   <view class="parent-category"><span style='font-size: 15px; font-weight: bold;'>商品编号：</span>{{ products.goods_sn }}</view>
		   <div>&nbsp;</div>
		   <view class="input-label">选择仓库</view>
		   <picker mode="selector" :range="ArrWareHouse" @change="onCooperationStatusChange" :value="0">
		     <view class="picker">{{ products.warehouse_name }}</view>
		   </picker>
	    </view>
	    <view class="modal-footer">
	      <button @click="submitProduct" class="action-button">提交</button>
	      <button @click="HideModel" class="action-button">取消</button>
	    </view>
	  </view>
	</view>
  </view>
</template>

<script>
import { config } from '../../config';
import { TokenStore } from '../../Store/TokenStore';
import { LoginState } from '../../util/LoginSate';

export default {
  data() {
    return {
      products: {
        id: null,
        goods_sn: '',
        goods_name: '',
        goods_spec: '',
        goods_price_in: null,
        goods_price_out: null,
        goods_status: '', // 假设这是一个字符串类型，如果是从数据库中获取，需要确保其长度不超过255字符
        goods_stock: '',
		category_name: '',
		warehouse_name:'',
		warehouse_id:null
      },
      showProductModal: false,
	  showWareHouseModal:false,
	  ArrWareHouse:[],
	  WareHouse:[{}]
    };
  },
  onLoad(options) {
	  if(!LoginState()){
	  	uni.showToast({
	  	  title: '登录失效',
	  	  icon: 'error'
	  	});
		uni.redirectTo({
			url:"/pages/index/index"
		})
	  	return ;
	  }
    this.products.goods_sn = options.good_sn; // 从页面参数中获取 good
    this.GetGoods(); // 调用方法
	console.log("生命周期被调用")
  },
  methods: {
    // 从后端接收数据
    GetGoods() {
      console.log("前端数据:" + JSON.stringify(this.products))
      uni.request({
        url: `${config.baseURL}/NGoods/GetGoods`,
        method: 'POST',
        data: this.products,
        header: {
          'content-type': 'application/json', // 设置请求头为 JSON
          'Authorization': TokenStore().token // 确保 TokenStore 函数已定义
        },
        success: (res) => {
          if (res.data.data === 'error') {
            uni.showToast({
              title: '数据库错误',
              icon: 'error'
            });
          } else {
            // 使用 Object.assign 或者展开运算符来更新 this.products，以保持响应性
			const productData = JSON.parse(res.data.data);
			Object.assign(this.products, productData);
			if(productData.warehouse_id === 0){
				this.products.warehouse_name = '请选择仓库'
			}
			console.log("后端返回:" + JSON.stringify(this.products));
			console.log("所属仓库名称为："+this.products.warehouse_name);
          }
        },
        fail: (err) => {
          uni.showToast({
            title: err.errMsg,
            icon: 'error'
          });
        }
      });
    },
    editProduct() {
      this.showProductModal = true;
    },
    shelveProduct() {
		if(this.products.warehouse_name === '请选择仓库'){
			uni.showToast({
			  title: '请先绑定仓库',
			  icon: 'error'
			});
			return ;
		}
      if(this.products.goods_status === '下架'){
		  this.products.goods_status = '上架'
	  }
	  else {
		  this.products.goods_status = '下架'
	  }
	  uni.request({
	  	url:`${config.baseURL}/NGoods/UpdateGoods`,
		method:'POST',
		data:this.products,
		header: {
		  'content-type': 'application/json', // 设置请求头为 JSON
		  'Authorization': TokenStore().token // 确保 TokenStore 函数已定义
		},
		success:(res)=>{
			if(res.data.data === '1'){
				uni.showToast({
				  title: '更改成功',
				  icon: 'success'
				});
				this.GetGoods()
			}
			else if(res.data.data === '0'){
				uni.showToast({
				  title: '系统繁忙',
				  icon: 'error'
				});
			}
			else if(res.data.data === 'error'){
				uni.showToast({
				  title: '数据库错误',
				  icon: 'error'
				});
			}
			else if(res.data.data === '令牌过期'){
				uni.showToast({
				  title: '请重新登录',
				  icon: 'error'
				});
			}
		},
		fail:(err)=>{
			uni.showToast({
			  title: err.errMsg,
			  icon: 'error'
			});
		}
	  })
    },
    onProductStatusChange(event) {
      this.products.goods_status = event.detail.value;
    },
    submitProduct() {
		if(this.products.warehouse_name === '请选择仓库'){
			uni.showToast({
			  title: '请先绑定仓库',
			  icon: 'error'
			});
			return ;
		}
      // 提交商品信息
      console.log("提交商品信息:" + JSON.stringify(this.products));
	  uni.request({
	  	url:`${config.baseURL}/NGoods/UpdateGoods`,
		method:'POST',
		data:this.products,
		header: {
		  'content-type': 'application/json', // 设置请求头为 JSON
		  'Authorization': TokenStore().token // 确保 TokenStore 函数已定义
		},
		success:(res)=>{
			if(res.data.data === '1'){
				uni.showToast({
				  title: '更改成功',
				  icon: 'success'
				});
				this.GetGoods()
				// 这里可以添加提交商品信息的逻辑
				this.showProductModal = false;
				this.showWareHouseModal = false;
			}
			else if(res.data.data === '0'){
				uni.showToast({
				  title: '系统繁忙',
				  icon: 'error'
				});
			}
			else if(res.data.data === 'error'){
				uni.showToast({
				  title: '数据库错误',
				  icon: 'error'
				});
			}
			else if(res.data.data === '令牌过期'){
				uni.showToast({
				  title: '请重新登录',
				  icon: 'error'
				});
			}
		},
		fail:(err)=>{
			uni.showToast({
			  title: err.errMsg,
			  icon: 'error'
			});
		}
	  })
    },
	//获取全部仓库数据
	AllWareHouse(){
		uni.request({
			url:`${config.baseURL}/Warehouse/AllWH`,
			method:'GET',
			header: {
			  'content-type': 'application/json', // 设置请求头为 JSON
			  'Authorization': TokenStore().token // 确保 TokenStore 函数已定义
			},
			success:(res)=>{
				if(res.data.data === 'error'){
					uni.showToast({
					  title: "数据库错误",
					  icon: 'error'
					});
					return ;
				}
				else {
					console.log("获取仓库信息成功"+res.data.data);
					let data = JSON.parse(res.data.data)
					this.WareHouse = data
					this.ArrWareHouse = data.map(item => item.warehouse_name);
					console.log("获取到仓库"+JSON.stringify(this.ArrWareHouse))
					return ;
				}
			},
			fail:(err)=>{
				uni.showToast({
				  title: err.errMsg,
				  icon: 'error'
				});
				return l
			}
		})
	},
	onCooperationStatusChange(e){
		this.products.warehouse_name = this.ArrWareHouse[e.target.value];
		console.log("仓库选择成功："+this.products.warehouse_name);
	},
	HideModel(){
		this.GetGoods()
		this.showProductModal = false;
		this.showWareHouseModal = false;
	}
  }
}
</script>

<style scoped>
.product-detail {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background-color: #f8f8f8;
}

.product-image {
  width: 100%;
  height: 300px;
  overflow: hidden;
  border-radius: 10px;
  margin-bottom: 20px;
}

.product-image image {
  width: 100%;
  height: 100%;
  border-radius: 10px;
}

.product-info {
  width: 100%;
  max-width: 500px;
  text-align: center;
  margin-bottom: 30px;
}

.product-name,
.product-code,
.product-inventory,
.product-cost,
.product-sale,
.product-status {
  margin-bottom: 10px;
  font-size: 16px;
  color: #333;
}

.action-buttons {
  display: flex;
  width: 100%;
  max-width: 500px;
  justify-content: space-between;
}

.edit-button,
.shelve-button {
  width: 48%;
  padding: 10px;
  background-color: #10a37f;
  color: white;
  border-radius: 5px;
  font-size: 16px;
  border: none;
  outline: none;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.shelve-button.shelved {
  background-color: #aaa;
}

.edit-button:hover,
.shelve-button:hover {
  background-color: #0e8b62;
}

.shelve-button:active {
  background-color: #0c6b4f;
}

/* 新增商品弹窗样式 */
.modal {
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  width: 90%;
  max-width: 500px; /* 限制弹窗的最大宽度 */
}
.modal-header {
border-bottom: 1px solid #eaeaea;
padding-bottom: 10px;
margin-bottom: 15px;
}

.modal-title {
font-size: 18px;
color: #333;
}

.modal-body {
margin-bottom: 15px;
}

.input-label {
font-size: 16px;
color: #333;
margin-bottom: 5px;
display: block; /* 使标签独占一行 */
}

.input-field-rounded {
width: 95%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #eaeaea;
border-radius: 4px;
font-size: 14px;
}

.picker {
display: flex;
justify-content: space-between;
padding: 10px;
border: 1px solid #eaeaea;
border-radius: 4px;
margin-bottom: 10px;
}

.modal-footer {
display: flex;
justify-content: flex-end;
}

.action-button {
padding: 10px 20px;
margin-left: 10px;
border: none;
border-radius: 4px;
background-color: #007bff;
color: white;
cursor: pointer;
font-size: 14px;
width: 55%;
height:53px;
}

.action-button:hover {
background-color: #0056b3;
}

.action-button:active {
transform: translateY(2px);
}
</style>